import 'package:city_pickers/city_pickers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Address.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/view_loading.dart';

class EditAddress extends StatefulWidget {
  Address address;

  EditAddress(this.address);

  @override
  _EditAddressState createState() => _EditAddressState();
}

class _EditAddressState extends State<EditAddress> {
  bool _loading = false;
  TextEditingController _nameController = TextEditingController();
  TextEditingController _phoneController = TextEditingController();
  TextEditingController _cityController = TextEditingController();
  TextEditingController _addressController = TextEditingController();
  String isDef = "0";

  @override
  void initState() {
    super.initState();
    if (null != widget.address) {
      _nameController.value = TextEditingValue(text: widget.address.realName);
      _phoneController.value = TextEditingValue(text: widget.address.telephone);
      _addressController.value = TextEditingValue(text: widget.address.street);
      String city =
          "${widget.address.province}/${widget.address.city}/${widget.address.area}";
      _cityController.value = TextEditingValue(text: city);
      isDef = widget.address.defAdds ? "1" : "0";
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        elevation: 0,
        backgroundColor: Theme.of(context).canvasColor,
        leading: IconButton(
            icon: Icon(Icons.arrow_back),
            onPressed: () {
              Routers.router.pop(context);
            }),
        automaticallyImplyLeading: false,
        title: Text(
          '添加地址',
          style: TextStyle(fontSize: 18),
        ),
      ),
      body: ProgressDialog(
        msg: "保存中...",
        loading: _loading,
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              _descWidget(),
              _nameWidget(),
              Divider(endIndent: 10, indent: 10, height: 0),
              _phoneWidget(),
              Divider(endIndent: 10, indent: 10, height: 0),
              _cityWidget(),
              Divider(endIndent: 10, indent: 10, height: 0),
              _addressWidget(),
              Divider(endIndent: 10, indent: 10, height: 0),
              _defaultWidget(),
              SizedBox(height: 20),
              _submitWidget(),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _cityController.dispose();
    _phoneController.dispose();
    _nameController.dispose();
    _addressController.dispose();
  }

  ///地址描述
  Widget _descWidget() {
    return Container(
      height: 40,
      width: double.infinity,
      color: Color(0xffF5F5F5),
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 10),
      child: Text(
        "地址信息",
        style: TextStyle(
          fontSize: 16,
          color: Color(0xff666666),
        ),
      ),
    );
  }

  ///姓名
  Widget _nameWidget() {
    return Container(
      width: double.infinity,
      color: Colors.white,
      child: TextField(
        controller: _nameController,
        maxLines: 1,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.all(10.0),
          hintText: "收货人姓名",
          hintStyle: TextStyle(
            fontSize: 16,
            color: Color(0xff999999),
          ),
          border: InputBorder.none,
        ),
      ),
    );
  }

  ///联系电话
  Widget _phoneWidget() {
    return Container(
      width: double.infinity,
      color: Colors.white,
      child: TextField(
        controller: _phoneController,
        maxLines: 1,
        keyboardType: TextInputType.phone,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.all(10.0),
          hintText: "联系电话",
          hintStyle: TextStyle(
            fontSize: 16,
            color: Color(0xff999999),
          ),
          border: InputBorder.none,
        ),
      ),
    );
  }

  ///省市区
  Widget _cityWidget() {
    return GestureDetector(
      child: Container(
        color: Colors.white,
        width: double.infinity,
        child: TextField(
          controller: _cityController,
          maxLines: 1,
          autofocus: false,
          enabled: false,
          keyboardType: TextInputType.phone,
          decoration: InputDecoration(
            contentPadding: EdgeInsets.all(10.0),
            hintText: "请选择城市",
            hintStyle: TextStyle(
              fontSize: 16,
              color: Color(0xff999999),
            ),
            border: InputBorder.none,
            suffixIcon: Icon(
              Icons.keyboard_arrow_down,
              color: Color(0xffCCCCCC),
            ),
          ),
        ),
      ),
      onTap: () async {
        Result data = await CityPickers.showCityPicker(
          context: context,
          height: 250,
          cancelWidget: Text(
            "取消",
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey,
            ),
          ),
          confirmWidget: Text(
            "确定",
            style: TextStyle(
              fontSize: 16,
              color: Theme.of(context).accentColor,
            ),
          ),
        );
        print("$data");
        if (null == data) {
          return;
        }
        String city = "${data.provinceName}/${data.cityName}/${data.areaName}";
        _cityController.value = TextEditingValue(text: city);
      },
    );
  }

  ///详细地址
  Widget _addressWidget() {
    return Container(
      width: double.infinity,
      color: Colors.white,
      child: TextField(
        controller: _addressController,
        maxLines: 4,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.all(10.0),
          hintText: "小区门牌号等详细地址",
          hintStyle: TextStyle(
            fontSize: 16,
            color: Color(0xff999999),
          ),
          border: InputBorder.none,
        ),
      ),
    );
  }

  ///默认地址选择
  Widget _defaultWidget() {
    return Container(
      height: 48,
      width: double.infinity,
      color: Colors.white,
      padding: EdgeInsets.only(left: 10),
      alignment: Alignment.centerLeft,
      child: Row(
        children: <Widget>[
          Text("设为默认地址", style: TextStyle(fontSize: 16)),
          SizedBox(width: 40),
          Text("是", style: TextStyle(fontSize: 16)),
          Radio(
            value: "1",
            groupValue: isDef,
            onChanged: (T) {
              setState(() {
                isDef = T;
              });
            },
          ),
          SizedBox(width: 20),
          Text("否", style: TextStyle(fontSize: 16)),
          Radio(
            value: "0",
            groupValue: isDef,
            onChanged: (T) {
              setState(() {
                isDef = T;
              });
            },
          ),
        ],
      ),
    );
  }

  ///保存按钮
  Widget _submitWidget() {
    return Container(
      width: double.infinity,
      height: 40,
      margin: EdgeInsets.only(left: 60, right: 60, top: 10),
      child: RaisedButton(
        child: Text(
          '保存',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
          ),
        ),
        color: Theme.of(context).accentColor,
        shape: StadiumBorder(
          side: BorderSide(
            color: Theme.of(context).accentColor,
          ),
        ),
        onPressed: () => _submit(),
      ),
    );
  }

  ///提交
  Future _submit() async {
    String realName = _nameController.text;
    String telephone = _phoneController.text;
    String city = _cityController.text;
    String address = _addressController.text;
    if (realName.isEmpty ||
        telephone.isEmpty ||
        city.isEmpty ||
        address.isEmpty) {
      Toast.show("请完善地址信息");
      return;
    }
    setState(() {
      _loading = true;
    });
    Map<String, Object> params = Map();
    if (null != widget.address) {
      params["addressId"] = widget.address.addressId;
    }
    params["realName"] = realName;
    params["telephone"] = telephone;
    params["province"] = city.split("/")[0];
    params["city"] = city.split("/")[1];
    params["area"] = city.split("/")[2];
    params["street"] = address;
    params["defAdds"] = isDef == "1";
    Http.post(Api.URL_ADDRESS_ADD, params: params, successCallBack: (data) {
      setState(() {
        _loading = false;
      });
      Toast.show("保存成功");
      Routers.router.pop(context);
    }, errorCallBack: (error) {
      setState(() {
        _loading = false;
      });
      Toast.show(error);
    });
  }
}
